package com.lujieni.netty.c3;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class EventLoopServer {

    public static void main(String[] args) {

        DefaultEventLoopGroup defaultEventLoopGroup = new DefaultEventLoopGroup(2);

        new ServerBootstrap()
                // boss only handle access event   worker handle read or write event on the channel
                .group(new NioEventLoopGroup(), new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast("handler1",new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                System.out.println(msg.getClass().getName());
                                if(msg instanceof ByteBuf){
                                    ByteBuf bb = (ByteBuf)msg;
                                    System.out.println(Thread.currentThread().getName()+" "+bb.toString(CharsetUtil.UTF_8));
                                }
                                ctx.fireChannelRead(msg); // notify next read handler to handle if u want
                            }
                        });

                        ch.pipeline().addLast(defaultEventLoopGroup,"handler2", new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                System.out.println(msg.getClass().getName());
                                if(msg instanceof ByteBuf){
                                    ByteBuf bb = (ByteBuf)msg;
                                    System.out.println(Thread.currentThread().getName()+" "+bb.toString(CharsetUtil.UTF_8));
                                }
                            }
                        });
                    }
                })
                .bind("localhost", 8080);


    }
}
